<template>
  <div id="app" :class="currentTheme">
    <!-- 加载动画 -->
    <div v-if="!isInitialized" class="init-loading">
      <div class="loading-container">
        <!-- Logo动画 -->
        <div class="loading-logo">
          <div class="logo-pulse"></div>
          <i class="el-icon-s-home"></i>
        </div>

        <!-- 进度条和状态 -->
        <div class="loading-progress">
          <el-progress
              type="circle"
              :percentage="loadingProgress"
              :status="loadingStatus"
              :stroke-width="6"
              v-bind="loadingStatus ? { status: loadingStatus } : {}">
          </el-progress>

          <!-- 任务状态列表 -->
          <div class="task-list">
            <div v-for="(task, index) in initTasks"
                 :key="task.name"
                 class="task-item"
                 :class="{
                   'completed': index < currentTaskIndex,
                   'current': index === currentTaskIndex,
                   'pending': index > currentTaskIndex
                 }">
              <i :class="getTaskIcon(index)"></i>
              <span>{{ task.name }}</span>
            </div>
          </div>

          <!-- 加载消息 -->
          <div class="loading-message">
            {{ loadingMessage }}
            <span class="loading-dots" v-if="!loadingStatus">
              <span></span>
              <span></span>
              <span></span>
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容，只有在初始化完成后才渲染 -->
    <template v-else>
      <router-view :key="$route.fullPath"></router-view>
      <WelcomeDialog :visible.sync="showWelcome"/>
    </template>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import WelcomeDialog from '@/components/common/WelcomeDialog.vue'
import {getSystemConfig, getCategoryList} from '@/api/portalAPI';
import {titleManager} from '@/router'
import constantsData from "@/constants";
import CacheUtil from "@/utils/CacheUtil";

export default {
  name: 'App',
  components: {
    WelcomeDialog
  },
  data() {
    return {
      showWelcome: false,
      isInitialized: false,
      loadingProgress: 0,
      loadingMessage: '正在初始化系统...',
      loadingStatus: undefined,
      initTasks: [
        {name: '系统配置', weight: 50},
        {name: '分类信息', weight: 50}
      ],
      currentTaskIndex: 0,
      vanishingTime: null
    }
  },
  computed: {
    ...mapState(['currentTheme'])
  },
  methods: {
    updateProgress(taskIndex, isSuccess = true) {
      const completedWeight = this.initTasks
          .slice(0, taskIndex + 1)
          .reduce((sum, task) => sum + task.weight, 0);
      this.loadingProgress = Math.floor((completedWeight / 100) * 100);

      if (!isSuccess) {
        this.loadingStatus = 'exception';
        this.loadingMessage = `${this.initTasks[taskIndex].name}加载失败，请刷新重试`;
      } else if (this.loadingProgress >= 100) {
        this.loadingStatus = 'success';
        this.loadingMessage = '初始化完成';
        setTimeout(() => {
          this.isInitialized = true;
        }, 500);
      } else {
        this.loadingStatus = undefined;
      }
    },

    async init() {
      try {
        // 初始化系统配置
        this.loadingMessage = '正在加载系统配置...';
        await this.initialize('系统配置', getSystemConfig, this.handleSystemConfigSuccess);
        this.updateProgress(0);

        // 初始化分类信息
        this.loadingMessage = '正在加载分类信息...';
        await this.initialize('分类信息', getCategoryList, this.handleCategoryListSuccess);
        this.updateProgress(1);

      } catch (error) {
        console.error('初始化失败:', error);
        this.loadingStatus = 'exception';
        this.loadingMessage = '系统初始化失败，请刷新页面重试';
      }
    },

    async initialize(itemName, apiCall, onSuccess) {
      try {
        console.log(`初始化${itemName}...`);
        const {code, data, msg} = await apiCall();
        if (code === 0) {
          console.log(`初始化${itemName}成功`);
          if (onSuccess) {
            await onSuccess(data);
          }
          return true;
        } else {
          console.error(`初始化${itemName}失败: ${msg}`);
          this.updateProgress(this.currentTaskIndex, false);
          return false;
        }
      } catch (error) {
        console.error(`初始化${itemName}失败:`, error);
        this.updateProgress(this.currentTaskIndex, false);
        return false;
      }
    },

    /**
     * 处理系统配置成功的后续逻辑
     * @returns {Promise<void>}
     */
    async handleSystemConfigSuccess(dataList) {
      for (const item of dataList) {
        await this.$cache.setItem(item.configKey, item);
      }
      const data = constantsData()
      titleManager.setSiteTitle(data.siteTitle + "-" + data.siteTitleDep)
    },
    /**
     * 处理分类信息成功的后续逻辑
     * @returns {Promise<void>}
     */
    async handleCategoryListSuccess(data) {
      const {topCategory, middleCategory, rightCategory} = data;
      await this.$cache.setItem('topCategory', this.buildTree(topCategory))
      await this.$cache.setItem('rightCategory', rightCategory)
      await this.$cache.setItem('middleCategory', middleCategory)
    },
    buildTree(categories) {
      const map = {};
      const tree = [];
      // 1. 将每个分类放入一个映射对象中，方便后续查找
      categories.forEach(category => {
        map[category.id] = {...category, children: []}; // 拷贝对象并初始化 children 数组
      });
      // 2. 遍历分类数据，根据 parentId 构建树形结构
      categories.forEach(category => {
        if (category.parentId === 0) {
          // 如果 parentId 为 0，说明是根节点
          tree.push(map[category.id]);
        } else {
          // 否则，将当前节点添加到其父节点的 children 中
          const parent = map[category.parentId];
          if (parent) {
            parent.children.push(map[category.id]);
          }
        }
      });
      return tree;
    },
    // 获取任务图标
    getTaskIcon(index) {
      if (index < this.currentTaskIndex) {
        return 'el-icon-check task-icon completed';
      } else if (index === this.currentTaskIndex) {
        return 'el-icon-loading task-icon current';
      }
      return 'el-icon-more task-icon pending';
    }
  },
  beforeMount() {
    this.init();
  },
  mounted() {
    // 检查是否首次访问
    this.vanishingTime = CacheUtil.getItem('vanishingTime')
    if (this.vanishingTime) {
      if (this.vanishingTime.starTime >= this.vanishingTime.endTime) {
        this.showWelcome = true
      } else {
        this.showWelcome = false
      }
    } else {
      this.showWelcome = true
    }
    // 监听系统主题变化
    this.$store.dispatch('initTheme')
    console.log('初始化完成')
  }
}
</script>

<style>
/* 全局变量 */
:root {
  /* 移除重复的CSS变量定义，改为只保留基础样式 */
}

/* 深色主题 */
.dark {
  /* 移除重复的CSS变量定义 */
}

/* 保留其他全局样式 */
#app {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  padding-top: 60px;
  min-height: 100vh;
  background-color: var(--bg-color);
  color: var(--text-color);
  transition: all 0.3s;
}

/* 全局滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
}

::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}

.main-content {
  max-width: var(--container-width);
  margin: 0 auto;
  padding: 20px; /* 添加两侧内边距 */
  display: flex;
  flex-direction: column;
  gap: var(--section-gap); /* 使用新的间距变量 */
}

@media (max-width: 1500px) {
  :root {
    --container-width: 1200px;
  }
}

@media (max-width: 1200px) {
  :root {
    --container-width: 960px;
  }
}

@media (max-width: 992px) {
  :root {
    --container-width: 720px;
  }
}

@media (max-width: 768px) {
  :root {
    --container-width: 100%;
  }

  .main-content {
    padding: 15px;
    gap: 15px;
  }

  #app {
    padding-top: 60px;
  }
}

/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

a {
  text-decoration: none;
  color: inherit;
}

/* 添加字体图标 */
/*@import url('//at.alicdn.com/t/c/font_4359570_qxiob2gw86.css');*/
/*@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');*/
/* 或者使用其他图标字体库，比如 Font Awesome */
/* @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css'); */

/* 调整卡片阴影，让它在深色背景上更明显 */
.card-bg {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 添加自定义加载样式 */
.el-loading-spinner {
  .el-loading-text {
    color: var(--text-color);
    font-size: 16px;
    margin-top: 10px;
  }

  .circular {
    .path {
      stroke: var(--primary-color); /* 使用主题色 */
    }
  }
}

/* 只添加必要的加载动画样式，确保类名唯一 */
.init-loading {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: var(--bg-color);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 30px;
  padding: 40px;
  background: var(--card-bg);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  min-width: 320px;
  animation: fadeIn 0.5s ease;
}

/* Logo 动画 */
.loading-logo {
  position: relative;
  width: 80px;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.loading-logo i {
  font-size: 36px;
  color: var(--primary-color);
  z-index: 2;
  animation: pulse 1.5s ease-in-out infinite;
}

.logo-pulse {
  position: absolute;
  width: 100%;
  height: 100%;
  border: 3px solid var(--primary-color);
  border-radius: 50%;
  animation: ripple 1.5s cubic-bezier(0, 0.2, 0.8, 1) infinite;
}

/* 进度条容器 */
.loading-progress {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  width: 100%;
}

/* 任务列表样式 */
.task-list {
  width: 100%;
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.task-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
  font-size: 14px;
}

.task-icon {
  width: 20px;
  text-align: center;
}

.task-item.completed {
  color: var(--success-color, #67C23A);
  background: rgba(103, 194, 58, 0.1);
}

.task-item.current {
  color: var(--primary-color, #409EFF);
  background: rgba(64, 158, 255, 0.1);
}

.task-item.pending {
  color: var(--text-color-secondary, #909399);
}

/* 加载消息样式 */
.loading-message {
  margin-top: 10px;
  color: var(--text-color);
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.loading-dots {
  display: inline-flex;
  gap: 4px;
  align-items: center;
}

.loading-dots span {
  width: 4px;
  height: 4px;
  background-color: currentColor;
  border-radius: 50%;
  animation: dotPulse 1.4s infinite;
}

.loading-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.loading-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

/* 动画关键帧 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes ripple {
  0% {
    transform: scale(0.8);
    opacity: 1;
  }
  100% {
    transform: scale(1.5);
    opacity: 0;
  }
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

@keyframes dotPulse {
  0%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  50% {
    transform: scale(1.2);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .loading-container {
    width: 90%;
    padding: 30px 20px;
    margin: 0 15px;
  }

  .loading-logo {
    width: 60px;
    height: 60px;
  }

  .loading-logo i {
    font-size: 28px;
  }
}
</style>
